package com.heqiang.spring.factory;

import com.heqiang.spring.BeansException;
import com.heqiang.spring.config.BeanDefinition;
import com.heqiang.spring.support.CglibSubclassingInstantiationStrategy;
import com.heqiang.spring.support.InstantiationStrategy;
import com.heqiang.spring.support.SimpleInstantiationStrategy;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
             bean = createBeanInstance(name, beanDefinition, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        //新增一个bean到单例中
        addSingleton(name,bean);
        return bean;
    }

    protected Object createBeanInstance(String name, BeanDefinition beanDefinition,Object[] args) {
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructor = ctor;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition,name,constructor,args);
    }

}
